<template>
  <div class="export-container">
	<div class="export-container-wrapper">
		<div class="i-left">
			<div class="header-box">
				<div class="btn-group">
					<el-upload
						ref="upload"
						:headers="upload.headers"
						:action="upload.url"
						:on-success="handleFileSuccess"
						:on-progress="handleFileUploadProgress"
						:on-error="handleFileUploadError"
						:disabled="upload.isUploading"
						accept=".csv"
						v-if="$store.state.user.roles[0]=='admin' || $store.state.user.roles[0]=='hichs'"
					>
						<el-button type="success" class="exportBtn" :loading="upload.isUploading">导入SN清单查询</el-button>
					</el-upload>
					<el-button type="primary" class="exportBtn" @click="getExportList" :disabled="!(multipleSelection.length>0)" v-if="$store.state.user.roles[0]=='admin' || $store.state.user.roles[0]=='hichs'">导出License清单</el-button>
				</div>
				<el-input placeholder="请输入当页显示license数量" v-model.number="inputPageSize" class="input">
				    <el-button slot="append" icon="el-icon-search" type="primary" @click="hanglePageSizeBtn"></el-button>
				</el-input>
			</div>
			<!-- <input type="text" v-model="queryParams.pageSize"><el-button type="primary" @click="handleGetList">查询</el-button> -->
			<el-table
			  :data="list"
			  v-loading="loading"
			  @selection-change="handleSelectionChange"
			 >
			  <el-table-column
			   v-if="$store.state.user.roles[0]=='admin' || $store.state.user.roles[0]=='hichs'"
			   show-overflow-tooltip
			   type="selection"
			   width="40">
			  </el-table-column>
			  <el-table-column
				prop="serial"
				label="序号"
				width="60">
			  </el-table-column>
			  <el-table-column
			   show-overflow-tooltip
				prop="sn"
				label="SN"
				min-width="80">
			  </el-table-column>
			  <el-table-column
				show-overflow-tooltip
				prop="uid"
				label="UID"
				min-width="105">
			  </el-table-column>
			  <el-table-column
				prop="status"
				label="状态"
				min-width="60">
			  </el-table-column>
			  <el-table-column
				label="生成日期"
				show-overflow-tooltip
				min-width="85">
				<template slot-scope="scope">
					{{scope.row.createTime | formatDate}}
				 </template>
			  </el-table-column>
			  <el-table-column
				label="出货日期"
				show-overflow-tooltip
				min-width="85">
				<template slot-scope="scope">
					{{scope.row.shippingDate | formatDate}}
				 </template>
			  </el-table-column>
			  <el-table-column
				prop="saleMan"
				label="销售人员"
				show-overflow-tooltip
				min-width="80">
			  </el-table-column>
			  <el-table-column
				label="使用日期"
				show-overflow-tooltip
				min-width="85">
				<template slot-scope="scope">
					{{scope.row.userTime | formatDate}}
				 </template>
			  </el-table-column>
			  <el-table-column
			    show-overflow-tooltip
				prop="customer"
				label="客户编码"
				min-width="80">
			  </el-table-column>
			  <el-table-column
			    show-overflow-tooltip
				prop="user"
				label="使用人"
				min-width="90">
			  </el-table-column>
			</el-table>
			<div class="pagination">
				<pagination
				  v-show="total>0"
				  :total="total"
				  :layout = "layout"
				  :page.sync="queryParams.pageNum"
				  :limit.sync="queryParams.pageSize"
				  @pagination="handleGetList"
				/>
			</div>
		</div>
		<div class="i-right">
			<div class="i-r-top">
				<div class="title">
					License总数
				</div>
				<div class="count">
					{{lincenseStatistics.total}}
				</div>
				<div class="statistics">
					<div class="left">
						有效数量：{{lincenseStatistics.available}}
					</div>
					<div class="right">
						无效数量：{{lincenseStatistics.invalid}}
					</div>
				</div>
			</div>
			<div class="i-r-bottom" v-if="$store.state.user.roles[0]=='admin' || $store.state.user.roles[0]=='hichs'">
				<div class="title">
					导入记录
				</div>
				 <el-table
				    ref="singleTable"
				    :data="exportRecord"
				    highlight-current-row
				    style="width: 100%;margin-top: 20px;">
				    <el-table-column
				 	  show-overflow-tooltip
				      property="filename"
				      label="名称"
				      width="120">
				    </el-table-column>
				    <el-table-column
				      property="record"
				      label="导入数量"
				      width="80">
				    </el-table-column>
					<el-table-column
					  show-overflow-tooltip
					  property="reportTime"
					  label="导入时间"
					  width="100">
					</el-table-column>
				  </el-table>
			</div>
		</div>
	</div>	
    
  </div>
</template>

<script>
import { getLicenseList, snRecordList, getFactoryTotalKey, exportNumber} from '@/api/export'
import { getToken } from "@/utils/auth";
import { mapGetters } from 'vuex';

mapGetters
export default {
	computed: {
	  ...mapGetters(['license_num'])
	},
  data() {
    return {
	  // 遮罩层
	  loading: false,
	  layout:'total, prev, pager, next, jumper',
	  multipleSelection: [],	//选中的行
	  upload: {
	    // 是否禁用上传
	    isUploading: false,
	    // 设置上传的请求头部
	    headers: { Authorization: "Bearer " + getToken() },
	    // 上传的地址
	    url: process.env.VUE_APP_BASE_API + "/licensekey/licensekeyFactory/csvImport"
	  },
	  //license清单
      list: [/* {
		id:1,
		sn:'xxx01',
		uid:'HICHS 0001-PX041',
		status:"有效",
		createTime: '20160502',
		shippingDate: '20160502',
		saleMan: '张三',
		userTime:'20160502',
		customer: '客户A',
		user:'生产人员A'
	  } */],
	  // 总条数
	  total: 0,
	  lincenseStatistics:{
	    total:0, 		//License总数
	    available:0,		//License有效数量
	    invalid:0			//License无效数
	  },
      // 导出记录,
	  exportRecord: [/* {
		name: '腾讯算法lincense',
		num: '19',
		date: '2016-05-02 12:41:05'
	  }, {
		name: '测试数据',
		num: '2772',
		date: '2016-05-04 12:41:05'
	  } */],
	  
	  // 查询参数
	  queryParams: {
	    pageNum: 1,
	    pageSize: 10,
	  },
	  inputPageSize:undefined
    }
  },
  created() {
    this.handleGetList();
	this.FactoryTotalKey();
	if(this.$store.state.user.roles[0]=='admin' || this.$store.state.user.roles[0]=='hichs'){
		this.getRecordList();
	}
  },
  methods: {
	//自定义页面显示license数量
	hanglePageSizeBtn(){
		let inputPageSize = this.inputPageSize
		if (!this.inputPageSize) {
			if(this.inputPageSize === 0){
				this.$message.info('请输入正确数量!');
				return
			}
			this.$message.info('请输入显示数量!');
		} else{
			this.queryParams.pageSize = this.inputPageSize;
			this.handleGetList()
		}
	},
	  
	//获取license列表
	handleGetList() {
	  this.loading = true;
	  getLicenseList(this.queryParams).then(response => {
		let { rows, total} = response;
		this.total = total;
		this.list = rows;
		this.loading = false;
	  });
	},
	
	//获取license统计
	FactoryTotalKey(){
	  	getFactoryTotalKey().then(response => {
			let {tot, tot1, tot2}  = response.data
			this.lincenseStatistics.total = tot;
			this.lincenseStatistics.available = tot1;
			this.lincenseStatistics.invalid = tot2;
	  	  })
	},
	
	//获取导入sn列表记录
	getRecordList(){
	  	snRecordList({type:2}).then(response => {
	  	    this.exportRecord = response.rows
	  	  })
	},
	// 文件上传中处理
	handleFileUploadProgress(event, file, fileList) {
	    this.upload.isUploading = true;
	},
	// 文件上传成功处理
	handleFileSuccess(response, file, fileList) {
		this.upload.isUploading = false;
		this.$refs.upload.clearFiles();
		this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
		this.handleGetList();
		this.getRecordList();
		this.FactoryTotalKey()
	},
	//文件上传失败处理
	handleFileUploadError(){
		
	},
	
	//表格多选变化触发
   handleSelectionChange(val) {
		this.multipleSelection = val;
    },
	//导出选中的license
	async getExportList(){
		const that = this
		let jsonData = {
			trade:{
				tHeader: ["序号","SN","UID","状态","生成日期","出货日期","销售人员","使用日期","客户","使用人"],
				filterVal: ["serial","sn","uid","status","createTime","shippingDate","saleMan","userTime","customer","user"],
				list: that.multipleSelection
			}
		}    
		that.exportPathMethod(jsonData)// 调用exportPathMethod对数据进行处理导出
		that.getExportNumber()
	},
	//导出license后台做记录，无任何功能
	getExportNumber(){
		exportNumber().then(response=>{
			console.log(response);
		})
	},
	exportPathMethod(data) {
		/*
		*注：csv文件：","逗号换列，\n换行，\t防止excel将长数字变科学计算法等样式
		*/
		//要导出的json数据
		let mainLists = data.trade   //主表
		let that = this
		//## 数据处理
		//一级表
		let mainTitle = mainLists.tHeader;//一级标题
		let mainTitleForKey = mainLists.filterVal;//一级过滤
		let mainList = mainLists.list;//一级数据
		let mainStr = [];
		mainStr.push(mainTitle.join("\t,")+"\n");   //标题添加上换列转成字符串并存进数组
		for(let i=0;i<mainList.length;i++){
			let temp = [];
			for(let j=0;j<mainTitleForKey.length;j++){
				temp.push(mainList[i][mainTitleForKey[j]]); //根据过滤器拿出对应的值
			}
			mainStr.push(temp.join("\t,")+"\n");    //取出来的值加上逗号换列转字符串存数组
		}
		// console.log(JSON.stringify(mainStr.join("")));//打印文本
	
		//两个表数组转成字符串合并
		let merged = mainStr.join("")
		//console.log(JSON.stringify(merged));//打印结果
		
		//## 导出操作
		// encodeURIComponent解决中文乱码
		// const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(merged)
		const uri = 'data:text/csv;charset=gbk,\ufeff' + encodeURIComponent(merged)
		// 通过创建a标签实现
		let link = document.createElement('a')
		link.href = uri
		// 对下载的文件命名
		// link.download = `用户信息${that.$moment(that.$moment().valueOf()).format('YYYYMMDD')}.csv`
		link.download = `License清单.csv`
		document.body.appendChild(link)
		link.click()
		
	}
  }
}
</script>
<style lang="scss" scoped>
	.export{
		&-container{
			
			&-wrapper{
				display: flex;
				justify-content: space-between;
				.i-left{
					margin-right: 20px;
					width: 100%;
					background-color: #fff;
					padding: 20px;
					box-shadow: 0 2px 10px 5px #eee;
					border-radius: 8px;
					.header-box{
						display: flex;
						justify-content: space-between;
						.btn-group{
							display: flex;
							.exportBtn{
								margin-bottom: 20px;
								margin-left: 20px;
								display: flex;
								height: 40px !important;
							}
						}
						.input{
							width: 270px;
							height: 41px;
						}
					}
					
				}
				.i-right{
					width: 500px;
					.i-r-top{
						background-color: #fff;
						margin-bottom: 20px;
						padding: 20px;
						box-shadow: 0 2px 10px 5px #eee;
						border-radius: 8px;
						.title{
							font-style: 14px;
							color: #333;
						}
						.count{
							font-size: 40px;
							text-align: center;
							padding: 15px 0 30px 0;
							
							
						}
						.statistics{
							display: flex;
							justify-content: center;
							font-size: 12px;
							.left{
								color: #1CA450;
								width: 120px;
								text-align: center;
							}
							.right: {
								color: #7E8590;
								width: 100px;
								text-align: center;
							};
						}
					}
					.i-r-bottom{
						border-radius: 8px;
						background-color: #fff;
						box-shadow: 0 2px 10px 5px #eee;
						padding: 20px;
						.title{
							font-style: 14px;
							color: #333;
						}
					}
				}
			}
		}
		
	}
</style>
